<template>
  <div id="actInfo">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" class="infoForm">
      <el-form-item prop="name" label="活动名称">
        <el-input v-model.trim="form.name" placeholder="请输入内容" :disabled="status==1"></el-input>  
      </el-form-item>
      <el-form-item prop="imageUrl" label="图片地址" v-if="actType.type!=='BIRTHDAY_TYPE'">
        <el-input v-model="form.imageUrl" placeholder="请输入内容" :disabled="status==1"></el-input>
        <upload @getImgInfo="getImgInfo"></upload>
      </el-form-item>
      <el-form-item label="是否分享" style="text-align:left;" v-if="actType.type!=='BIRTHDAY_TYPE'" >
        <template>
          <el-radio class="radio" v-model="form.shared" label="YES" :disabled="status==1">是</el-radio>
          <el-radio class="radio" v-model="form.shared" label="NO" :disabled="status==1">否</el-radio>
        </template>
      </el-form-item>
      <el-form-item label="活动时间" prop="dateArr">
        <el-date-picker
          v-model="form.dateStart"
          type="datetime"
          placeholder="选择日期时间" :disabled="status==1">
        </el-date-picker>
        <el-date-picker
          v-model="form.dateEnd"
          type="datetime"
          placeholder="选择日期时间" :disabled="status==1">
        </el-date-picker>
      </el-form-item>
      <el-form-item prop="url" label="活动url" v-if="actType.type!=='BIRTHDAY_TYPE'">
        <el-input v-model="form.url" placeholder="请输入内容" :disabled="status==1"></el-input>
      </el-form-item>
      <el-form-item prop="remark" label="活动描述">
        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入内容" v-model.trim="form.remark" :disabled="status==1">
        </el-input>
      </el-form-item>
    </el-form>
    <stepBtn :nextBtn="next" :successBtn="success" :prevBtn="prev" :saveBtn="save" :btnShow="btnShow" ></stepBtn>
  </div>
</template>
<script>
import upload from 'components/upload'
import stepBtn from '../stepButton.vue'
import moment from 'moment'
import {formRules} from './config'
import { createActivity, editActivity, activityDetail } from 'api/activity'
import { postLog } from 'api/common/index.js'
import { jsUtils } from 'util/util.js'
export default {
  components: {
    upload, stepBtn
  },
  props: ['edit'],
  data () {
    return {
      form: {
        creator: sessionStorage.getItem('realName') || sessionStorage.getItem('USER_NAME'),              //创建人 (登录的时候存在sessionStorage里面)
        type: JSON.parse(sessionStorage.getItem('actType')).type,                                        //活动类型
        name: '',                                                                                        //活动名称
        imageUrl: '',                                                                                    //图片url
        status: 'WARM_UP',                                                                               //是否开始
        shared: 'YES',                                                                                   //是否分享
        url: '',                                                                                         //活动url
        remark: '',                                                                                      //活动描述
        dateStart: '',                                                                                   //活动开始时间
        dateEnd: ''                                                                                      //活动结束时间
      },
      dateStart: '',
      rules: formRules,                                                                                  //校验规则
      btnShow: {                                                                                         //控制按钮展示
        next: false,
        prev: true,
        save: false,
        success: false
      },
      nextTap: '',                                                                                       //下一步的名称
      nowIndex: ''                                                                                       //现在处于第几步
    }
  },
  created () {
    if (!this.edit) {
      this.checkStep();
    } else {
      this.btnShow.save = true
      this.btnShow.prev = false
    }
    if (sessionStorage.getItem('activityId')) {
      this.getActivityDetail()
    }
  },
  computed: {
    //活动类型 步骤
    actTypeInfo () {
      return JSON.parse(sessionStorage.getItem('addActivityType'))
    },
    //活动类型
    actType () {
      return JSON.parse(sessionStorage.getItem('actType'))
    },
    status () {
      return sessionStorage.getItem('actStatus')
    }
  },
  methods: {
    async getActivityDetail () {
      try {
        let back = await activityDetail(sessionStorage.getItem('activityId'))
        back = back.data
        if (back.resultCode === '200') {
          let data = {
            text: back.result.info.typeText,
            type: back.result.info.type
          }
          sessionStorage.setItem('actType', JSON.stringify(data))
          this.form.type = back.result.info.type
          this.form.name = back.result.info.name
          this.form.imageUrl = back.result.info.imageUrl
          this.form.status = back.result.info.status
          this.form.shared = back.result.info.shared
          this.form.url = back.result.info.url
          this.form.remark = back.result.info.remark
          this.form.dateStart = back.result.info.dateStart
          this.form.dateEnd = back.result.info.dateEnd
        } else {
          this.$alert(back.msg)
        }
      } catch (err) {
        this.$alert('请求失败', '提示')
      }
    },
    checkStep () {
      let stepArr = this.actTypeInfo.relatedSectionsArray
      //现在处于第几步
      this.nowIndex = stepArr.indexOf('INFO')
      //下一步
      let nextIndex = this.nowIndex + 1
      // 如果这是最后一步了
      if (nextIndex === stepArr.length) {
        this.btnShow.success = true;
      } else {
        this.btnShow.next = true;
        this.nextTap = stepArr[nextIndex]
      }
    },
    getImgInfo (result) {
      this.form.imageUrl = result.file_path;
    },
    success () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let form = {...this.form}
          if (form.dateStart === '' || form.dateStart === '') {
            this.$alert('请输入活动时间', '提示')
            return
          }
          form.dateStart = moment(this.form.dateStart).format('YYYY-MM-DD HH:mm:ss')
          form.dateEnd = moment(this.form.dateEnd).format('YYYY-MM-DD HH:mm:ss')
          this.submit(form, 'success')
          return true
        } else {
          return false
        }
      })
    },
    next () {
      // this.$emit('changePageShow', this.nextTap)
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let form = {...this.form}
          if (form.dateStart === '' || form.dateStart === '') {
            this.$alert('请输入活动时间', '提示')
            return
          }
          form.dateStart = moment(this.form.dateStart).format('YYYY-MM-DD HH:mm:ss')
          form.dateEnd = moment(this.form.dateEnd).format('YYYY-MM-DD HH:mm:ss')
          this.submit(form, 'next')
          return true
        } else {
          return false
        }
      })
    },
    prev () {
      this.$emit('changePageShow', 'TYPE', 'prev')
    },
    save () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let form = {...this.form}
          if (form.dateStart === '' || form.dateStart === '') {
            this.$alert('请输入活动时间', '提示')
            return
          }
          form.dateStart = moment(this.form.dateStart).format('YYYY-MM-DD HH:mm:ss')
          form.dateEnd = moment(this.form.dateEnd).format('YYYY-MM-DD HH:mm:ss')
          this.submit(form, 'save')
          return true
        } else {
          return false
        }
      })
    },
    /**
     * @param form 经过校验的活动基本信息form表单
     * @param type 接口调用成功后的操作
     */
    async submit (form, type) {
      if (jsUtils.compTime(form.dateStart, form.dateEnd) === 'equal') {
        this.$alert('开始时间与结束时间相等', '提示')
        return
      } else if (jsUtils.compTime(form.dateStart, form.dateEnd) === 'less') {
        this.$alert('开始时间小于结束时间', '提示')
        return
      }
      if (JSON.parse(sessionStorage.getItem('actType')).type === 'BIRTHDAY_TYPE') {
        delete form.shared
      }
      if (sessionStorage.getItem('activityId')) {
        form.id = Number(sessionStorage.getItem('activityId'))
        try {
          let back = await editActivity(form)
          back = back.data
          if (back.resultCode === '200') {
          // 成功日志
            postLog('ACTIVITY_LIST_EDIT', '', form.name, form)
            if (type === 'next') {
              this.$emit('changePageShow', this.nextTap)
            } else if (type === 'success') {
              this.$router.push({name: 'activityList'})
            } else if (type === 'save') {
              this.$alert('保存成功', '提示')
            }
          } else {
            this.$alert(back.msg)
          }
        } catch (err) {
          this.$alert('请求出错', '提示')
        }
        return
      }
      try {
        let back = await createActivity(form)
        back = back.data
        if (back.resultCode === '200') {
          // 成功日志
          postLog('ACTIVITY_LIST_CREATE', '', form.name, form)
          sessionStorage.setItem('activityId', back.result.id)
          if (type === 'next') {
            this.$emit('changePageShow', this.nextTap)
          } else if (type === 'success') {
            this.$router.push({name: 'activityList'})
          } else if (type === 'save') {
            this.$alert('保存成功', '提示')
          }
        } else {
          this.$alert(back.msg)
        }
      } catch (err) {
        this.$alert('请求出错', '提示')
      }
    }
  }
}
</script>
<style lang="less" scoped>
  .infoForm{
    width:600px;
  }
</style>
